import flask
from flask import Blueprint, request, redirect, url_for, session, make_response

demo1 = Blueprint("demo1", __name__)


@demo1.route('/demo')
def demo():
    return "another page."


@demo1.route("/")
def home_index():
    return flask.render_template("index.html")


@demo1.route("/chatgpt")
def chatgpt_index():
    return flask.render_template("chat_gpt.html")


@demo1.route("/chat")
def chat_index():
    return flask.render_template("chat_index.html")


# 满足RESTful 命名语法规范
@demo1.route("/user", methods=['POST'])
def user_register():
    return 'OK'


@demo1.route('/session', methods=['post'])
def user_login():
    user_name = request.form.get('user_name')
    pass_word = request.form.get('pass_word')
    if user_name != 'admin' or pass_word != 'admin':
        return 'bad request'
    return 'login success'


@demo1.route('/redirect')
def p_red():
    # return redirect('/')
    return redirect(url_for('home_index'), code=301)


@demo1.route('/redirectjs')
def p_redjs():
    # return redirect('/')
    js = '10s redirect'
    js += '<script>setTimeout(function(){location.href=\'/\'},5000)</script>'
    # return redirect(url_for('home_index'),code=301)
    return js


@demo1.route('/test/<int:chating_num>')
def test_func(chating_num):
    return 'you are reading %d' % chating_num


@demo1.route('/sess')
def get_sess():
    session['isLogin'] = True
    session['name'] = 'zc'
    session['age'] = 31
    return 'ok'


@demo1.route('/sess/read')
def read_sess():
    session['name'] = 'zc'
    session['age'] = 31
    return 'name' + session['name'] + 'age:' + str(session['age'])


@demo1.route('/cookie')
def get_cookie():
    resp = make_response('Make resp')
    resp.set_cookie('name', 'zcc', 1000)
    resp.set_cookie('age', '45', 1000)
    return resp


@demo1.route('/cookie/read')
def read_cookie():
    cookie = request.cookies
    return cookie
